<template>
	<view class="fill-order-info">
		<basic-nav-bar 
          backgroundColor="#fff"
          :statusBar="true"
          :border="false" 
          :fixed="true"
          left-icon="arrowleft" 
          title="填写订单信息" />
		<view class="order-info" v-if="bookCheckInfo.bookCheckProductReleases">
			<view class="title">
				{{bookCheckInfo.bookCheckProductReleases[0].name}}				
			</view>
			<!-- bookCheckInfo.bookCheckProductReleases[0].productType == 3 (3-门票；1-线路)-->
			<basic-label-value label="套餐" v-if="bookCheckInfo.bookCheckProductReleases[0].productType == 1" :value="bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].name" color="#333333" size="28rpx"/>
			<basic-label-value label="游玩日期" v-if="bookCheckInfo.bookCheckProductReleases[0].productType == 3" :value="bookCheckInfo.checkin" color="#333333" size="28rpx"/>
			<basic-label-value label="出行日期" v-if="bookCheckInfo.bookCheckProductReleases[0].productType == 1" :value="bookCheckInfo.checkin" color="#333333" size="28rpx"/>	
			<view class="skuList" v-if="skuList.length > 0">
				<p v-for="(sku, index) in skuList" :key="index">{{bookCheckInfo.bookCheckProductReleases[0].productType !== 3 ? sku.name : '门票'}}&nbsp;&nbsp;x&nbsp;&nbsp;{{sku.bookNum}}</p>
			</view>
			<view class="order-info-price">
			  <basic-price :price="totalPrice" size="36rpx" color="#FF5944" unitSize="30rpx"  />				
			</view>
		</view>
		
		<view class="form-wrap">
			<u-form :model="form" ref="orderForm" label-position="top" >
				<formLayout title="联系信息" v-if="contacts.length > 0">
					<u-form-item 
						v-for="(item, index) in contacts" 
						:key="index" 
						:label="item.fieldName" 
						:prop="FIELDNAMETYPE[item.fieldNameType]+'-contact'" 
						:required="item.isRequired===1?true:false"
						@click="showSelect"
					>			
					     <!-- 性别		 -->													
						<view class="select-value" :class="{hasValue: form[FIELDNAMETYPE[item.fieldNameType]+'-contact']}"
							v-if="item.fieldNameType == 103" 
							@click="showSelect(FIELDNAMETYPE[item.fieldNameType]+'-contact')" 
						>
							{{form[FIELDNAMETYPE[item.fieldNameType]+'-contact'] ? formatFild(FIELDNAMETYPE[item.fieldNameType], form[FIELDNAMETYPE[item.fieldNameType]+'-contact'] ): '请选择'+item.fieldName}}								
						</view>
						<!-- 日期 -->
						<view v-else-if="isTime(item.fieldNameType)" class="select-value" :class="{hasValue: form[FIELDNAMETYPE[item.fieldNameType]+'-contact']}" @click="timeFocus(item.fieldNameType, FIELDNAMETYPE[item.fieldNameType]+'-contact')" >
							{{form[FIELDNAMETYPE[item.fieldNameType]+'-contact'] ? form[FIELDNAMETYPE[item.fieldNameType]+'-contact']: '请选择'+item.fieldName}}								
						</view>	
						<!-- 整数类型 -->
						<!-- <u-input 
						    v-else-if="isInt(FIELDNAMETYPE[item.fieldNameType])"
							v-model="form[FIELDNAMETYPE[item.fieldNameType]+'-contact']"
							:placeholder="'请填写'+item.fieldName" 
							type="number"
							:clearable="false"
						/>						 -->
						<u-input 
							v-else
							v-model="form[FIELDNAMETYPE[item.fieldNameType]+'-contact']"
							:placeholder="'请填写'+item.fieldName" 
							type="string"
							:clearable="false"
						/>
					</u-form-item>					
				</formLayout>
				<view class="" v-for="(passenger, INDEX) in passengers" :key="INDEX"  v-if="passengers.length > 0">
					<formLayout :title="'出行人信息'+ (passengers.length > 1 ? INDEX+1 : '') ">					
						<u-form-item 
							v-for="(item, index) in passenger" 
							:key="index" 
							:label="item.fieldName" 
							:prop="FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX" 
							:required="item.isRequired===1?true:false"
						>
						    <!-- 性别		 -->							
							<view class="select-value" :class="{hasValue: form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX]}"
								v-if="item.fieldNameType == 103"
								@click="showSelect(FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX)" 								
							>
								{{form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX] ? formatFild(FIELDNAMETYPE[item.fieldNameType], form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX] ): '请选择性别'}}								
							</view>
							<!-- 日期 -->
							<view v-else-if="isTime(item.fieldNameType)" class="select-value" :class="{hasValue: form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX]}" @click="timeFocus(item.fieldNameType, FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX)" >
								{{form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX] ? form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX]: '请选择'+item.fieldName}}								
							</view>
							<!-- 整数类型 -->
							<!-- <u-input 
								v-else-if="isInt(FIELDNAMETYPE[item.fieldNameType])"
								v-model="form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX]"
								:placeholder="'请填写'+item.fieldName" 
								type="number"
								:clearable="false"
							/> -->
							<!-- 其他类型输入 -->
							<u-input 
								v-else
								v-model="form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+INDEX]"
								:placeholder="'请填写'+item.fieldName" 
								:clearable="false"
							/>
						</u-form-item>					
					</formLayout>
						
				</view>
				<formLayout title="其他信息" v-if="others.length > 0">
					<u-form-item 
					    v-for="(item, index) in others" 
						:key="index" 
						:label="item.fieldName" 
						:prop="OTHERSINFO[item.fieldNameType]+'-others'" 
						:required="item.isRequired===1?true:false"
					>
					    <!-- 日期类型 -->
					    <view v-if="isTime(item.fieldNameType)" class="select-value" :class="{hasValue: form[OTHERSINFO[item.fieldNameType]+'-others']}" @click="timeFocus(item.fieldNameType, OTHERSINFO[item.fieldNameType]+'-others')" >
							{{form[OTHERSINFO[item.fieldNameType]+'-others'] ? form[OTHERSINFO[item.fieldNameType]+'-others']: '请选择'+item.fieldName}}								
						</view>
						<!-- 整数类型 -->
						<!-- <u-input 
							v-else-if="isInt(OTHERSINFO[item.fieldNameType]+'-others')"
							v-model="form[OTHERSINFO[item.fieldNameType]+'-others']"
							:placeholder="'请填写'+item.fieldName" 
							type="number"
							:clearable="false"
						/> -->
						<u-input 
						    v-else
							v-model="form[OTHERSINFO[item.fieldNameType]+'-others']"
							:placeholder="'请填写'+item.fieldName" 
							:clearable="false"
						/>
					</u-form-item>					
				</formLayout>
			</u-form>			
		</view>	

		<!-- 性别选择 -->
		<u-select  v-model="showGenderSelect" mode="mutil-column-auto" :list="genderList" @confirm="genderConfirm"></u-select>	
		<!-- 日期选择 -->
		<we-picker v-model="showTimePicker" mode="time" :params="timeParams" @confirm="timeConfirm"></we-picker>

		<!-- 费用明细 -->
		<uni-popup ref="priceDetail" type="bottom" >
		   <priceDetail :totalPrice="totalPrice" :skuList="skuList" @close="$refs.priceDetail.close()"></priceDetail>
		</uni-popup>
		<fill-bottom-bar :totalPrice="totalPrice" @showPriceDetail="showPriceDetail" @submit="submit" />	
	</view>
</template>
<script>
import formLayout from '@/components/business/form-layout'
import wePicker from '@/components/business/we-picker'
import fillBottomBar from './components/fill-bottom-bar'
import priceDetail from './components/price-detail'
import { getBookCheck, createOrder } from 'api'
import {decodeQueryObject} from 'utils/helper/query'
import store from '@/store'
import { FIELDNAMETYPE, OTHERSINFO, ORDERITEMNAME, genderList } from '@/model/enum'
import goPay from 'utils/goPay'
import ua from 'utils/ua'
import sdk from 'sdk'
import storage from 'utils/helper/storage'
import {formatTime} from 'utils/helper/date-handle'
import { rules } from './params'
import { formatFild } from 'utils/helper/common'
export default {
	name: '',
	components: {
		formLayout,
		fillBottomBar,
		priceDetail,
		wePicker
	},
	data() {
		return {
			showTimePicker: false,
			timeParams: { year: true, month: true, day: true, hour: true, minute: true, second: false },
			timeFormat: 'yyyy-MM-dd hh:mm:ss',
			options: {},
			bookCheckInfo: {},
			skuList:[],
			totalPrice:0,
			contacts:[],//联系人
			passengers:[],//出行人
			others:[],//其他
			FIELDNAMETYPE,
			OTHERSINFO,
			ORDERITEMNAME,
			form: {},
			formRules: {},
			rules:rules(this),
			showGenderSelect: false,
			genderList,
			formKey:null,
			skuNum:0
		}
	},
	onReady() {
	},
	created() {
		this.getBookCheck()
	},
	onLoad(query){
		this.options = decodeQueryObject(query)
        // 每个需要m站登录的页面都需要加下面这段代码，否则接口不带token，一直要登录
		const { mToken } = this.options
		if(mToken) store.commit('SAVE_TOKEN', { token: mToken })
	},
	methods: {
		isTime(typeNum){ // 判断是否是时间选择项
			const timeList = [104,205,206,407,408,409,10005,10006,10024,10023]
			if(timeList.indexOf(typeNum)!=-1) return true
			return false
		},
		// isInt(name){
		// 	const intList = ['weight','countryId','height','luggageCount',"playDay"]
		// 	if(intList.indexOf(name)!=-1) return true
		// 	return false
		// },
		setTimeParams(year,month,day,hour,minute,second){
			this.timeParams = { year, month, day, hour, minute, second }
		},
		timeFocus(typeNum, key){ // 点击输入框的处理
			if([104,205,206,10023].indexOf(typeNum) > -1){ // yyyy-mm-dd 10023-备选日期
				this.setTimeParams(true,true,true,false,false,false)
				this.timeFormat = 'yyyy-MM-dd'
			}
			if([10024,10006,407].indexOf(typeNum) > -1){ // hrs:min  10024-备选日期  10006-用车时间 407-出发时间
				this.setTimeParams(false,false,false,true,true,false)
				this.timeFormat = 'hh:mm'
			}
			if([408,409].indexOf(typeNum) > -1){ // yyyy-mm-dd-hrs-min 408-航班起飞时间 409-航班抵达时间
				this.setTimeParams(true,true,true,true,true,false)
				this.timeFormat = 'yyyy-MM-dd hh:mm'
			}
			this.showTimePicker = true	
			this.formKey = key	     
		},
		timeConfirm(e){
			let time = ''
			this.form[this.formKey] = formatTime(e,this.timeFormat)
		},
		formatFild:formatFild,
		showSelect(key){
			this.showGenderSelect = true
			this.formKey = key
		},
		submit() {
			console.log('this.form::', this.form,'this.formRules:', this.formRules,  )
			if (JSON.stringify(this.form) === '{}') {
				const params = {
					subOrders:this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases,
				}
				this.createOrder(params)
				return
			}
			this.$refs.orderForm.validate(valid => {
				if (valid) {
					console.log('验证通过');
					// 处理表单数据
					let contact = {}
					let passengers = []
					let itinerary = {}
					for (let key in this.form) {
						if(key.indexOf('-contact') > -1){
						   let contcatKey = key.split('-')[0]
						   if(key.indexOf('gender') > -1){ contact[contcatKey] = parseInt(this.form[key]) }
						   else contact[contcatKey] = this.form[key]
						}
						if(key.indexOf('-passenger') > -1){
						   let passengerKey = key.split('-')[0]
						   let arrIndex = key.split('-')[2]
						   let p = {}
						   if(key.indexOf('gender') > -1){ p[passengerKey] = parseInt(this.form[key]) }
						   else p[passengerKey] = this.form[key]
						   let w = passengers[arrIndex]?passengers[arrIndex]:null
						   passengers[arrIndex] = {...p,...w}
						//    passengers[arrIndex][passengerKey] = this.form[key]
						}
						if(key.indexOf('-others') > -1){
						   let otherKey = key.split('-')[0]
						   //    itinerary[otherKey] = this.form[key]
							// 处理需要传object对象的字段
							let objName = ['selectedBranch','startOffLocation','getToLocation','returnOutboundCity','returnStartLocation','overnightHotel','assemblingPlace']
							if(objName.indexOf(otherKey) > -1){
								let newElement = null
								if(!this.form[key]){
									newElement = null
									itinerary[otherKey] = newElement
								}else{
									itinerary[otherKey] = {'name':this.form[key]}
								}
							}else{
								itinerary[otherKey] = this.form[key]
							}
						}
					}
					const params = {
						contact,
						passengers,
						itinerary,
						subOrders:this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases,
					}				
					
					this.createOrder(params)
					
				} else {
					console.log('验证失败');
				}
			});
		},
		createOrder(params){
			sdk.showLoading({mask: true})
			createOrder(params).then(res=>{
				sdk.hideLoading({mask: true})
				// 创建订单成功后，跳支付页面
				if(res && res.code === 0){
					let orderNo = res.result ? res.result : ''
					goPay(orderNo, 'replace', () => {
						// TODO 待优化（跳转逻辑和业务耦合）
						// 为了防止app中支付页面返回订单填写页，需要该页面和订单填写页共享同一个窗口
						// 拉起支付后需要返回选择规格页面
						if (ua.isAppWebview) {
							uni.navigateBack()
						}
					})
				}else {
					sdk.showToast({
						icon: 'none',
						title: '订单创建失败'
					})
				}
			}).catch(()=>{
				sdk.showToast({
					icon: 'none',
					title: '订单创建失败'
				})
			})
		},
		getBookCheck(){
			const params = storage.get('fill_order_sku')
			getBookCheck(params).then(res=>{	
				if(res && res.code === 0){
					this.bookCheckInfo = res.result ? res.result : {}
					this.skuList = this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases
					this.getTotalPrice(this.skuList)
					this.getSukNum()
					this.persons()
                }
			})
		},
		showPriceDetail(){
			this.$refs.priceDetail.open()
		},
		getTotalPrice(skuList){
			this.totalPrice = 0
			skuList.map(sku => {
				this.totalPrice += (sku.bookNum * sku.price * 1)
				sku.productNum = sku.bookNum
                sku.checkinTime = this.bookCheckInfo.checkin
            })
		},
		getSukNum() {
            // productType=1或者3 1是线路  3是门票  出行人数量另外算
            if(this.bookCheckInfo.bookCheckProductReleases[0].productType === 1 || this.bookCheckInfo.bookCheckProductReleases[0].productType === 3){
                this.bookCheckInfo &&
                this.bookCheckInfo.bookCheckProductReleases && 
                this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases && 
                this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases.map(sku => {
					this.skuNum += sku.bookNum
                })
            }else{
                this.skuNum = this.bookCheckInfo.bookCheckProductReleases[0].bookCheckPackageReleases[0].bookCheckSkuReleases.length
            }
        },
		persons(){
			const { passengerType, bookConfigReleases } = this.bookCheckInfo.bookCheckProductReleases[0]
			let bookConfigs = bookConfigReleases
			this.contacts = []
			this.passengers = []
			this.others = []
			let passenger = []
			this.form = {}
			this.formRules = {}
            bookConfigs.map(item => {
                if(item.infoType === 1){ // 联系人
					this.contacts.push(item)
					this.form[FIELDNAMETYPE[item.fieldNameType]+'-contact']=null
					this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-contact']=[]
					if(item.isRequired==1){
						this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-contact'].push({ required: true, message: '请输入'+ORDERITEMNAME[FIELDNAMETYPE[item.fieldNameType]], trigger: 'blur,change' })
					}
					if(this.rules[FIELDNAMETYPE[item.fieldNameType]]){
						this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-contact'].push(...this.rules[FIELDNAMETYPE[item.fieldNameType]])
					}
                }else if(item.infoType === 2){ // 出行人
					passenger.push(item)
                }else if(item.infoType === 3){ // 其他
					this.others.push(item)					
					this.form[OTHERSINFO[item.fieldNameType]+'-others']=null
					this.formRules[OTHERSINFO[item.fieldNameType]+'-others']=[]
					if(item.isRequired==1){
						this.formRules[OTHERSINFO[item.fieldNameType]+'-others'].push({ required: true, message: '请输入'+ORDERITEMNAME[OTHERSINFO[item.fieldNameType]], trigger: 'blur,change' })
					}
					if(this.rules[OTHERSINFO[item.fieldNameType]]){
						this.formRules[OTHERSINFO[item.fieldNameType]+'-others'].push(...this.rules[OTHERSINFO[item.fieldNameType]])
					}
                }
			})
			// 1:至少需要一个出行人 2：需要全部出行人 3：不需要出行人
            if(passengerType === 1){
                this.passengers.push(passenger)
            }else if(passengerType === 2){
				for (let index = 0; index < this.skuNum; index++) {
					this.passengers.push(passenger)
				}
            }else if(passengerType === 3){
                this.passengers = []
			}
			this.passengers.map((passengerItem,index)=>{
				passengerItem.map((item)=>{
					this.form[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+index]=''
					this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+index]=[]
					if(item.isRequired==1){
						this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+index].push({required: true, message: '请输入'+ORDERITEMNAME[FIELDNAMETYPE[item.fieldNameType]], trigger: 'blur,change' })
					}
					if(this.rules[FIELDNAMETYPE[item.fieldNameType]]){
						this.formRules[FIELDNAMETYPE[item.fieldNameType]+'-passenger-'+index].push(...this.rules[FIELDNAMETYPE[item.fieldNameType]])
					}
				})				
			})
			this.form={...this.form}
			this.$refs.orderForm.setRules(this.formRules);
		},
		genderConfirm(e) {
			this.form[this.formKey] = e[0].value
		}
	}
}
</script>
<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
</style>
<style lang="less">
.fill-order-info{
	background: #F2F2F2;
	height: 100vh;
	.order-info{
		border-top: 1rpx solid #EAEAEA;
		padding: 20rpx 30rpx 30rpx;
		margin-bottom: 20rpx;
		background: #fff;
		.title{
			color:#333333;
			font-size: 32rpx;
			line-height: 60rpx;
			font-weight: 600;
		}
		.skuList{
			line-height: 50rpx;
		}
		.order-info-price{
			margin-top: 10rpx;
		}
	}	

	.select-value{
		height: 70rpx;
		width: 100%;
		color: rgb(192, 196, 204);
		display: flex;
		align-items: center;
		&.hasValue{
			color: #303133
		}
	}
}

</style>